<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author Cheng
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'supervisor:approval:process:supervisorApproval:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="supervisor_approval_process"
        completeText="提交"
        :completeModal="true"
        :loading="loadingRef"
        :auth="'supervisor:approval:process:supervisorApproval:edit'"
        @validate="handleValidate"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsSupervisorApprovalProcessSupervisorApprovalForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { SupervisorApproval, supervisorApprovalSave, supervisorApprovalForm } from '/@/api/supervisor.approval.process/supervisorApproval';
  import { BpmButton } from '/@/components/Bpm';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('supervisor.approval.process.supervisorApproval');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<SupervisorApproval>({} as SupervisorApproval);
  const loadingRef = ref(false);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增超时监督员审批流程') : t('编辑超时监督员审批流程'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('主流程id  由那个流程发起的'),
      field: 'mainProcessId',
      component: 'Input',
      rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('隐患类型'),
      field: 'hazardType',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
    {
      label: t('企业ID'),
      field: 'enterpriseId',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
    {
      label: t('企业名称'),
      field: 'enterpriseName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
    {
      label: t('建筑ID'),
      field: 'buildId',
      component: 'Input',
      rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('建筑名称'),
      field: 'buildName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
    {
      label: t('区域ID'),
      field: 'regionId',
      component: 'Input',
      rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('区域名称'),
      field: 'regionName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
    {
      label: t('隐患说明'),
      field: 'hazardDescription',
      component: 'Input',
    },
    {
      label: t('是否超时'),
      field: 'isTimeout',
      component: 'Input',
    },
    {
      label: t('创建时间'),
      field: 'createTime',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
    },
    {
      label: t('延期时间'),
      field: 'delayTime',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
    },
    {
      label: t('监督员姓名'),
      field: 'supervisorName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
    {
      label: t('监督员code'),
      field: 'supervisorCode',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
    {
      label: t('流程状态  已完成  未完成'),
      field: 'processStatus',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
    {
      label: t('将流程中的id保存'),
      field: 'redisTaskCache',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { md: 24, lg: 12 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await supervisorApprovalForm(data);
    record.value = (res.supervisorApproval || {}) as SupervisorApproval;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });

  async function handleValidate(_event: any, formData: any) {
    try {
      const data = await validate();
      formData(true, data); // 将表单数据传递给 BpmButton
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    }
  }

  async function handleSubmit(event: any) {
    try {
      loadingRef.value = true;
      const data = event?.formData || (await validate()); // 接受 BpmButton 传递过来的表单数据
      data.bpm = Object.assign(data.bpm || {}, record.value.bpm); // 流程信息
      data.status = record.value.status; // 提交状态
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        tid: record.value.tid,
      };
      // console.log('submit', params, data, record);
      const res = await supervisorApprovalSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
